package com.satan.vote.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.satan.vote.entity.VoteItem;
import com.satan.vote.mapper.VoteItemMapper;
import com.satan.vote.service.VoteItemService;
import com.satan.vote.util.DateUtil;
import com.satan.vote.vo.ResultVO;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName VoteItemServiceImpl
 * @Description TODO
 * @date 2023/8/13 16:06
 * @Version 1.0
 */
@Service
public class VoteItemServiceImpl extends ServiceImpl<VoteItemMapper, VoteItem> implements VoteItemService {
    @Value("${voteItemImagesFilePath}")
    private String voteItemImagesFilePath;
    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    @Transactional
    public void add(VoteItem voteItem) {
        save(voteItem);
    }

    @Override
    public ResultVO uploadVoteItemImage(MultipartFile voteItemImage) throws IOException {
        System.out.println("filename:" + voteItemImage.getName());
        Map<String, Object> resultMap = new HashMap<>();
        if (!voteItemImage.isEmpty()) {
            // 获取文件名
            String originalFilename = voteItemImage.getOriginalFilename();
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = DateUtil.getCurrentDateStr() + suffixName;
            String uniappFolderPath = null;
            try {
                // 获取 resources 目录的路径
                String resourcesPath = resourceLoader.getResource("classpath:").getFile().getAbsolutePath();

                // 拼接 uniapp 文件夹的路径
                uniappFolderPath = resourcesPath + File.separator + voteItemImagesFilePath;

                // 创建 Path 对象
                Path uniappFolder = Paths.get(uniappFolderPath);

                // 判断 uniapp 文件夹是否存在
                if (Files.exists(uniappFolder) && Files.isDirectory(uniappFolder)) {
                    System.out.println("uniapp 文件夹已存在");
                } else {
                    // 创建 uniapp 文件夹
                    Files.createDirectory(uniappFolder);
                    System.out.println("uniapp 文件夹创建成功");
                }
            } catch (Exception e) {
                System.out.println("发生异常：" + e.getMessage());
            }
            try {
                FileUtils.copyInputStreamToFile(voteItemImage.getInputStream(), new File(uniappFolderPath, newFileName));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            resultMap.put("voteItemImageFileName", newFileName);
            return ResultVO.success(resultMap);
        }
        return ResultVO.fail(500, "上传失败");
    }

    @Override
    public ResultVO getRankByVoteId(Integer voteId) {
//        new QueryWrapper<VoteItem>().eq("vote_id", voteId).orderByDesc("number")\
        QueryWrapper queryWrapper = QueryWrapper.create().where(VoteItem::getVoteId).eq(voteId).orderBy(VoteItem::getNumber).desc();
        List<VoteItem> voteItemList = list(queryWrapper);
        return ResultVO.success(voteItemList);
    }
}
